<template>
  <div class="lum-dialog-mask">
    <el-container class="lum-dialog-box">
      <el-header class="header" height="50px">
        <p>选择头像</p>
        <p class="tools">
          <el-icon @click="close(0)"><ele-Close /></el-icon>
        </p>
      </el-header>
      <el-main class="main">
        <el-container class="full-height">
          <el-aside width="400px">
            <div class="cropper-box">
              <vue-cropper
                ref="cropper"
                mode="cover"
                :img="option.img"
                :output-size="option.size"
                :output-type="option.outputType"
                :info="true"
                :full="option.full"
                :fixed="fixed"
                :fixed-number="fixedNumber"
                :can-move="option.canMove"
                :can-move-box="option.canMoveBox"
                :fixed-box="option.fixedBox"
                :original="option.original"
                :auto-crop="option.autoCrop"
                :auto-crop-width="option.autoCropWidth"
                :auto-crop-height="option.autoCropHeight"
                :center-box="option.centerBox"
                :high="option.high"
                @real-time="realTime"
              />
              <input
                type="file"
                id="uploads"
                ref="fileInput"
                accept="image/png, image/jpeg, image/jpg"
                style="display: none"
                @change="uploadImg($event, 1)"
              />
            </div>
            <div class="tools tools-flex">
              <el-button
                size="default"
                plain
                :icon="Upload"
                @click="clickUpload"
                type="primary"
                >上传图片
              </el-button>
              <el-button
                size="default"
                plain
                :icon="Refresh"
                @click="refreshCrop"
                >刷新
              </el-button>
              <el-button
                size="default"
                plain
                :icon="RefreshLeft"
                @click="rotateLeft"
                >左转
              </el-button>
              <el-button
                size="default"
                plain
                :icon="RefreshRight"
                @click="rotateRight"
                >右转
              </el-button>
            </div>
          </el-aside>
          <el-main class="no-padding">
            <div class="cropper-box">
              <div class="preview-img">
                <img v-if="cusPreviewsImg" :src="cusPreviewsImg" />
              </div>
            </div>
            <div class="tools">
              <el-button type="primary" size="small" @click="uploadService">
                保存图片
              </el-button>
            </div>
          </el-main>
        </el-container>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { VueCropper }  from "vue-cropper";
import 'vue-cropper/dist/index.css'
import { reactive, toRefs, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Upload, Refresh, RefreshLeft, RefreshRight } from '@element-plus/icons-vue'
import { useChatApi } from '/@/api/chat'

export default {
    name: 'AvatarCropper',
    components: {
        VueCropper
    },
    setup(props, context) {
        const fileInput = ref()
        const cropper = ref()
        const chatApi = useChatApi()
        const state = reactive({
            cusPreviewsImg: '',
            previews: {},
            option: {
                img: '',
                size: 1,
                full: false,
                outputType: 'png',
                canMove: true,
                fixedBox: true,
                original: false,
                canMoveBox: true,
                autoCrop: true,
                // 只有自动截图开启 宽度高度才生效
                autoCropWidth: 200,
                autoCropHeight: 150,
                centerBox: false,
                high: true,
            },
            fixed: true,
            fixedNumber: [1, 1]
        })
        const close = (type) => {
            context.emit('close', type)
        }
        const clickUpload = () => {
            fileInput.value.click()
        }
        const clearCrop = () => {
            if (!state.cusPreviewsImg) return false
            cropper.value.clearCrop()
        }
        const refreshCrop = () => {
            if (!state.cusPreviewsImg) return false
            cropper.value.refresh()
        }
        const rotateLeft = () => {
            if (!state.cusPreviewsImg) return false
            cropper.value.rotateLeft()
        }
        const rotateRight = () => {
            if (!state.cusPreviewsImg) return false
            cropper.value.rotateRight()
        }
        // 实时预览函数
        const realTime = () => {
            cropper.value.getCropData(img => {
                state.cusPreviewsImg = img
            })
        }
        // 上传回调事件
        const uploadImg = (e, num) => {
            let file = e.target.files[0]
            if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
                ElMessage.error('图片类型必须是.gif,jpeg,jpg,png,bmp中的一种')
                return false
            }
            let reader = new FileReader()
            reader.onload = e => {
                let data
                if (typeof e.target.result === 'object') {
                // 把Array Buffer转化为blob 如果是base64不需要
                    data = window.URL.createObjectURL(new Blob([e.target.result]))
                } else {
                    data = e.target.result
                }
                if (num === 1) {
                    state.option.img = data
                } else if (num === 2) {
                    state.example2.img = data
                }
            }
            // 转化为base64
            // reader.readAsDataURL(file)
            // 转化为blob
            reader.readAsArrayBuffer(file)
        }
        // 上传图片到服务器
        const uploadService = () => {
            if (state.cusPreviewsImg == '') return
            cropper.value.getCropBlob(blob => {
                let file = new File([blob], 'avatar.png', {
                    type: blob.type,
                    lastModified: Date.now(),
                })
                const form = new FormData()
                form.append('file', file)
                chatApi.ServeUploadAvatar(form).then(res => {
                    if (res.code == 0) {
                        context.emit('close', 1, res.data.avatar)
                    } else {
                        ElMessage.error('文件上传失败,请稍后再试...')
                    }
                }).catch(() => {
                    ElMessage.error('文件上传失败,请稍后再试...')
                })
            })
        }
        return {
            ...toRefs(state),
            close,
            uploadService,
            uploadImg,
            realTime,
            rotateRight,
            rotateLeft,
            refreshCrop,
            clearCrop,
            clickUpload,
            cropper,
            Upload,
            Refresh,
            RefreshLeft,
            RefreshRight,
            fileInput
        }
    }
}
</script>

<style lang="scss" scoped>
.lum-dialog-box {
  height: 550px;
  max-width: 700px;

  .main {
    .cropper-box {
      height: 400px;
      display: flex;
      justify-content: center;
      align-items: center;

      .preview-img {
        width: 180px;
        height: 180px;
        border-radius: 50%;
        overflow: hidden;
        box-shadow: 0 0 4px #ccc;

        img {
          width: 100%;
          height: 100%;
        }
      }
    }

    .tools {
      height: 40px;
      margin-top: 20px;
      text-align: center;

      button {
        border-radius: 1px;
      }
    }

    .tools-flex {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
    }
  }
}
</style>